#define pinA 2//digital 2/int.0
#define pinB 3//digital 3/int.1
//#define unit 1//每个中断变化的距离

uint8_t state = 0;//电平状态记录 A'B'AB
long int cnt = 0;//距离计数器
//每个状态数值作为数组元素索引，对应距离的变化
const int8_t distanceChange[15]={0,1,-1,0,-1,0,0,1,1,0,0,-1,0,-1,1};


void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  initEncoder();//初始化编码器
  
  
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.print("PULSE:");
Serial.println(cnt);

cnt = 0;
delay(100);
}


void initEncoder(){
  
attachInterrupt(0,encoderIntFun,CHANGE);
attachInterrupt(1,encoderIntFun,CHANGE);
pinMode(pinA,INPUT);
pinMode(pinB,INPUT);

boolean A = digitalRead(2);
  boolean B = digitalRead(3);
  state = state<<1;
  state = state&A;
  state = state<<1;
  state = state&B;

}

void encoderIntFun(){
  boolean A = digitalRead(2);
  boolean B = digitalRead(3);
  state = state<<1;
  state = state|A;
  state = state<<1;
  state = state|B;
  state = state&15;//只保留后四位
  cnt = cnt + distanceChange[state];
}
